<template>
  <div class="admin-management">
    <h1>管理员管理</h1>

    <!-- 查询管理员 -->
    <div class="search-section">
      <label for="search-username">用户名查询：</label>
      <input
          v-model="searchQuery"
          type="text"
          id="search-username"
          placeholder="输入用户名查询"
          class="input-field"
          @keydown.enter="fetchAdmins"
      />
      <button @click="fetchAdmins" class="search-button">
        <i class="fas fa-search"></i> 查找
      </button>
    </div>

    <!-- 提示信息 -->
    <transition name="fade">
      <div v-if="message" :class="messageClass" class="toast">{{ message }}</div>
    </transition>

    <!-- 管理员列表 -->
    <div class="table-container" v-if="isLoading">
      <p class="loading-text">加载中...</p>
    </div>
    <div class="table-container" v-else-if="admins.length > 0">
      <table class="admin-table">
        <thead>
        <tr>
          <th>ID</th>
          <th>头像</th>
          <th>用户名</th>
          <th>密码</th>
          <th>头像链接</th>
          <th>创建时间</th>
          <th>角色</th>
          <th>负责地区</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="admin in admins" :key="admin.adminId">
          <td>{{ admin.adminId }}</td>
          <td>
            <img
                :src="admin.avatarUrl"
                alt="头像"
                class="avatar"
                v-if="admin.avatarUrl"
            />
            <span v-else>暂无头像</span>
          </td>
          <td>{{ admin.username }}</td>
          <td>{{ truncateText(admin.passwordHash) }}</td>
          <td>{{ truncateText(admin.avatarUrl) }}</td>
          <td>{{ formatDate(admin.createdAt) }}</td>
          <td>{{ admin.role }}</td>
          <td>{{ admin.region }}</td>
          <td class="action-buttons">
            <button @click="deleteAdmin(admin.username)" class="action-button delete">
              <i class="fas fa-trash-alt"></i> 删除
            </button>
            <button @click="openEditModal(admin)" class="action-button edit">
              <i class="fas fa-edit"></i> 修改
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <div v-else class="no-data">暂无管理员数据</div>

    <!-- 增加管理员按钮 -->
    <button @click="openAddModal" class="submit-button">
      <i class="fas fa-plus"></i> 新增管理员
    </button>

    <!-- 增加/修改管理员弹窗 -->
    <div v-if="isModalOpen" class="modal">
      <div class="modal-content">
        <h2>{{ isEditMode ? '修改管理员' : '新增管理员' }}</h2>
        <form @submit.prevent="handleFormSubmit" enctype="multipart/form-data">
          <div class="form-group">
            <label for="username">用户名：</label>
            <input v-model="currentAdmin.username" type="text" id="username" required class="input-field" />
          </div>
          <div class="form-group">
            <label for="password">密码：</label>
            <input v-model="currentAdmin.passwordHash" type="password" id="password" required class="input-field" />
          </div>
          <div class="form-group">
            <label for="region">地区：</label>
            <div class="region-selector">
              <input
                  v-model="regionInput"
                  @input="filterRegions"
                  @keydown.enter="selectFirstRegion"
                  @focus="showDropdown = true"
                  @blur="hideDropdown"
                  type="text"
                  id="region"
                  placeholder="输入地区名称"
                  required
                  class="input-field"
              />
              <ul v-if="showDropdown && filteredRegions.length > 0" class="region-dropdown">
                <li
                    v-for="region in filteredRegions"
                    :key="region"
                    @mousedown="selectRegion(region)"
                    class="region-option"
                >
                  {{ region }}
                </li>
              </ul>
            </div>
          </div>
          <div class="form-group">
            <label for="role">角色：</label>
            <select v-model="currentAdmin.role" id="role" required class="input-field">
              <option value="common">普通管理员</option>
              <option value="super">超级管理员</option>
            </select>
          </div>
          <div class="form-group">
            <label for="file">头像：</label>
            <input type="file" @change="handleFileChange" id="file" class="input-field" />
          </div>
          <div class="form-actions">
            <button type="submit" class="submit-button">
              <i class="fas fa-check"></i> 提交
            </button>
            <button @click="closeModal" type="button" class="cancel-button">
              <i class="fas fa-times"></i> 取消
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      admins: [],
      totalAdmins: 0,
      searchQuery: '',
      message: '',
      messageType: '',
      isModalOpen: false,
      isEditMode: false,
      isLoading: true,
      currentAdmin: {
        id: null,
        username: '',
        passwordHash: '',
        region: '',
        role: '',
        avatarUrl: ''
      },
      avatarFile: null,
      regionInput: '',
      showDropdown: false,
      regions: [
        '渝中区', '江北区', '南岸区', '沙坪坝区', '九龙坡区', '大渡口区', '北碚区', '渝北区', '巴南区',
        '长寿区', '江津区', '合川区', '永川区', '南川区', '綦江区', '大足区', '璧山区', '铜梁区', '潼南区',
        '荣昌区', '开州区', '梁平区', '武隆区', '涪陵区', '万州区', '黔江区', '城口县', '丰都县', '垫江县',
        '忠县', '云阳县', '奉节县', '巫山县', '巫溪县', '石柱土家族自治县', '秀山土家族苗族自治县',
        '酉阳土家族苗族自治县', '彭水苗族土家族自治县'
      ],
      filteredRegions: []
    };
  },
  computed: {
    messageClass() {
      return this.messageType === 'success' ? 'toast success' : 'toast error';
    }
  },
  watch: {
    'currentAdmin.region'(newVal) {
      this.regionInput = newVal;
      this.filterRegions();
    }
  },
  methods: {
    async fetchAdmins() {
      this.isLoading = true;
      try {
        const token = this.$store.state.token;
        let response;

        if (this.searchQuery) {
          response = await axios.get('/api/admin/getAdminByUsername', {
            params: { username: this.searchQuery },
            headers: { Authorization: token },
          });

          if (response.status === 200) {
            if (typeof response.data === 'string' && response.data === '管理员不存在') {
              this.admins = [];
              this.message = '管理员不存在';
              this.messageType = 'error';
            } else {
              this.admins = [response.data];
              this.message = '查询成功';
              this.messageType = 'success';
            }
          }
        } else {
          response = await axios.get('/api/admin/getAllAdmins', {
            headers: { Authorization: token },
          });

          if (response.status === 200) {
            this.admins = Array.isArray(response.data) ? response.data : [];
            this.totalAdmins = this.admins.length;
            this.message = this.admins.length > 0 ? '数据加载成功' : '暂无数据';
            this.messageType = 'success';
          }
        }
      } catch (error) {
        const status = error.response?.status;
        const errorMessage = error.response?.data || '未知错误';
        switch (status) {
          case 401:
            this.message = '无效的 Token，请重新登录';
            break;
          case 404:
            this.message = errorMessage === '管理员不存在' ? '管理员不存在' : '资源未找到';
            break;
          case 500:
            this.message = '服务器内部错误，请稍后重试';
            break;
          default:
            this.message = '获取数据失败，请重试';
        }
        this.messageType = 'error';
        this.admins = [];
      }
      this.isLoading = false;
      this.clearMessage();
    },
    async deleteAdmin(username) {
      if (!confirm(`确定删除管理员 ${username} 吗？`)) return;
      try {
        const token = this.$store.state.token;
        const response = await axios.delete('/api/admin/deleteAdmin', {
          params: { username },
          headers: { Authorization: token },
        });

        if (response.status === 200) {
          this.message = `管理员 ${username} 删除成功`;
          this.messageType = 'success';
          this.fetchAdmins();
        }
      } catch (error) {
        const status = error.response?.status;
        const errorMessage = error.response?.data || '未知错误';
        switch (status) {
          case 400:
            this.message = errorMessage || '请求错误，请检查输入';
            break;
          case 401:
            this.message = '无效的 Token，请重新登录';
            break;
          case 500:
            this.message = '服务器内部错误，请稍后重试';
            break;
          default:
            this.message = '删除失败，请重试';
        }
        this.messageType = 'error';
      }
      this.clearMessage();
    },
    openAddModal() {
      this.isModalOpen = true;
      this.isEditMode = false;
      this.currentAdmin = { id: null, username: '', passwordHash: '', region: '', role: '', avatarUrl: '' };
      this.regionInput = '';
      this.filterRegions();
    },
    openEditModal(admin) {
      this.isModalOpen = true;
      this.isEditMode = true;
      this.currentAdmin = { ...admin };
      this.regionInput = admin.region;
      this.filterRegions();
    },
    closeModal() {
      this.isModalOpen = false;
      this.showDropdown = false;
      this.message = '';
    },
    handleFileChange(event) {
      this.avatarFile = event.target.files[0];
    },
    async handleFormSubmit() {
      if (!this.currentAdmin.region || !this.regions.includes(this.currentAdmin.region)) {
        this.message = '请选择有效的地区';
        this.messageType = 'error';
        this.clearMessage();
        return;
      }
      try {
        const token = this.$store.state.token;
        const formData = new FormData();
        formData.append('adminRequest', new Blob([JSON.stringify(this.currentAdmin)], { type: 'application/json' }));
        if (this.avatarFile) {
          formData.append('file', this.avatarFile);
        }

        const url = this.isEditMode ? '/api/admin/updateAdmin' : '/api/admin/addAdmin';
        const response = await axios.post(url, formData, {
          headers: { Authorization: token },
        });

        if (response.status === 200) {
          this.message = this.isEditMode ? '管理员修改成功' : '管理员添加成功';
          this.messageType = 'success';
          this.closeModal();
          this.fetchAdmins();
        }
      } catch (error) {
        const status = error.response?.status;
        const errorMessage = error.response?.data || '未知错误';
        switch (status) {
          case 400:
            this.message = errorMessage || '请求错误，请检查输入';
            break;
          case 401:
            this.message = '无效的 Token，请重新登录';
            break;
          case 403:
            this.message = '权限不足';
            break;
          case 500:
            this.message = '服务器内部错误，请稍后重试';
            break;
          default:
            this.message = '操作失败，请重试';
        }
        this.messageType = 'error';
      }
      this.clearMessage();
    },
    truncateText(text, maxLength = 20) {
      if (!text) return '';
      return text.length > maxLength ? text.slice(0, maxLength) + '...' : text;
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
    },
    clearMessage() {
      setTimeout(() => {
        this.message = '';
        this.messageType = '';
      }, 3000);
    },
    filterRegions() {
      if (!this.regionInput) {
        this.filteredRegions = this.regions;
      } else {
        this.filteredRegions = this.regions.filter(region =>
            region.toLowerCase().includes(this.regionInput.toLowerCase())
        );
      }
      this.showDropdown = true;
    },
    selectRegion(region) {
      this.currentAdmin.region = region;
      this.regionInput = region;
      this.showDropdown = false;
    },
    selectFirstRegion() {
      if (this.filteredRegions.length > 0) {
        this.selectRegion(this.filteredRegions[0]);
      }
    },
    hideDropdown() {
      setTimeout(() => {
        this.showDropdown = false;
      }, 200);
    }
  },
  mounted() {
    this.fetchAdmins();
  },
};
</script>

<style scoped>
.admin-management {
  padding: 5px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 96px);
}

h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1F2937;
  text-align: center;
  margin-bottom: 24px;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
  justify-content: center;
}

.search-section label {
  font-size: 14px;
  color: #4B5563;
}

.input-field {
  padding: 10px 14px;
  font-size: 14px;
  border: 1px solid #E5E7EB;
  border-radius: 6px;
  background: #F9FAFB;
  width: 260px;
  height: 15px;
  transition: border-color 0.2s ease;
}

.input-field:focus {
  outline: none;
  border-color: #3B82F6;
}

.region-selector {
  position: relative;
  width: 100%;
}

.region-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  background: #ffffff;
  border: 1px solid #E5E7EB;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  list-style: none;
  padding: 0;
  margin: 0;
}

.region-option {
  padding: 8px 14px;
  font-size: 14px;
  color: #374151;
  cursor: pointer;
}

.region-option:hover {
  background: #EFF6FF;
  color: #3B82F6;
}

.search-button {
  padding: 10px 20px;
  background: #3B82F6;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.2s ease;
}

.search-button:hover {
  background: #2563EB;
}

.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  z-index: 2000;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.toast.success {
  background: #D1FAE5;
  color: #065F46;
}

.toast.error {
  background: #FEE2E2;
  color: #991B1B;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.table-container {
  margin-bottom: 24px;
  overflow-x: auto;
}

.admin-table {
  width: 100%;
  border-collapse: collapse;
}

.admin-table th,
.admin-table td {
  padding: 12px 16px;
  text-align: left;
  font-size: 14px;
  color: #374151;
}

.admin-table th {
  background: #F3F4F6;
  font-weight: 600;
  color: #1F2937;
}

.admin-table tr:nth-child(even) {
  background: #F9FAFB;
}

.admin-table tr:hover {
  background: #EFF6FF;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  vertical-align: middle;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-button {
  padding: 8px 14px;
  font-size: 13px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.2s ease;
}

.action-button.delete {
  background: #EF4444;
  color: #ffffff;
}

.action-button.delete:hover {
  background: #DC2626;
}

.action-button.edit {
  background: #F59E0B;
  color: #ffffff;
}

.action-button.edit:hover {
  background: #D97706;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #6B7280;
  font-size: 14px;
}

.loading-text {
  text-align: center;
  padding: 20px;
  color: #6B7280;
  font-size: 14px;
}

.submit-button {
  padding: 10px 20px;
  background: #10B981;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.2s ease;
}

.submit-button:hover {
  background: #059669;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: #ffffff;
  padding: 24px;
  border-radius: 12px;
  max-width: 500px;
  width: 90%;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-content h2 {
  font-size: 20px;
  color: #1F2937;
  margin-bottom: 20px;
  text-align: center;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  font-size: 14px;
  color: #4B5563;
  margin-bottom: 6px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px 14px;
  font-size: 14px;
  border: 1px solid #E5E7EB;
  border-radius: 6px;
  background: #F9FAFB;
  transition: border-color 0.2s ease;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3B82F6;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.cancel-button {
  padding: 10px 20px;
  background: #6B7280;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.2s ease;
}

.cancel-button:hover {
  background: #4B5563;
}
</style>